import pymysql

class DButils:

    def __init__(self, host, user, password, database, port=3306, charset='utf8'):
        self.host = host
        self.user = user
        self.password = password
        self.database = database
        self.port = port
        self.charset = charset

    def update(self, sql,data=None):
        db = pymysql.connect(
            host=self.host,
            user=self.user,
            password=self.password,
            database=self.database,
            port=self.port,
            charset=self.charset
        )
        try:
            with db.cursor() as cursor:
                cursor.execute(sql,data)
                db.commit()
                print('数据操作成功！')
        except Exception as e:
            print('数据操作失败！',e)
        finally:
            db.close()

    def select(self, sql,data=None):
        db = pymysql.connect(
            host=self.host,
            user=self.user,
            password=self.password,
            database=self.database,
            port=self.port,
            charset=self.charset
        )
        try:
            with db.cursor() as cursor:
                cursor.execute(sql,data)
                result = cursor.fetchall()
                return result
        except Exception as e:
            print('数据查询失败！',e)
        finally:
            db.close()

if __name__ == '__main__':
    db = DButils('127.0.0.1', 'root', 'root', 'company')
    # sql = 'select * from t_dept'
    # result = db.select(sql)
    # print(result)
    sql = "update t_dept set loc=%s where deptno=%s"
    parm = ('北京',8)
    db.update(sql,parm)






















